﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessObjects;
using BusinessLogic;
using DCMS_Framework;

namespace Presentation.Children {
  /// <summary>
  /// Trustperson form
  /// </summary>
  public partial class TrustPersonForm : Form {

    private ZipcodeBll zipcodeBll = new ZipcodeBll( );
    private SortableBindingList<CityZipcode> zipcodeList;
    private TrustPersons trustPersonList = new TrustPersons( );
    private TrustPersons originalList = new TrustPersons( );
    private TrustPersonBll bll = new TrustPersonBll( );
    private int childId;

    #region - Properties -

    /// <summary>
    /// Gets or sets the trust person list.
    /// </summary>
    /// <value>
    /// The trust person list.
    /// </value>
    public TrustPersons TrustPersonList {
      get { return trustPersonList; }
      set { trustPersonList = value; }
    }

    #endregion

    #region - Constructors -

    public TrustPersonForm( ) {
      InitializeComponent( );
    }

    public TrustPersonForm( BusinessObjects.TrustPersons trustPersons, int selectedId )
      : this( ) {
      trustPersonList = trustPersons;
      this.trustPersonBindingSource.DataSource = trustPersonList;

      this.openPictureFileDialog.Filter = "jpg files (*.jpg)|*.jpg|png files (*.png)|*.png|bmp files|*.bmp|All files (*.*)|*.*";

      this.nameTextBox.DataBindings.Add( new Binding( "Text", this.trustPersonBindingSource, "Name", true, DataSourceUpdateMode.OnPropertyChanged ) );
      this.firstNameTextBox.DataBindings.Add( new Binding( "Text", this.trustPersonBindingSource, "FirstName", true, DataSourceUpdateMode.OnPropertyChanged ) );
      this.phoneTextBox.DataBindings.Add( new Binding( "Text", this.trustPersonBindingSource, "Phone", true, DataSourceUpdateMode.OnPropertyChanged ) );
      this.gsmTextBox.DataBindings.Add( new Binding( "Text", this.trustPersonBindingSource, "Gsm", true, DataSourceUpdateMode.OnPropertyChanged ) );
      this.emailTextBox.DataBindings.Add( new Binding( "Text", this.trustPersonBindingSource, "Email", true, DataSourceUpdateMode.OnPropertyChanged ) );
      this.nationalNumberTextBox.DataBindings.Add( new Binding( "Text", this.trustPersonBindingSource, "NationalNumber", true, DataSourceUpdateMode.OnPropertyChanged ) );
      this.useChildLinkCheckBox.DataBindings.Add( new Binding( "Checked", this.trustPersonBindingSource, "UseChildLink", true, DataSourceUpdateMode.OnPropertyChanged ) );
      this.photoPictureBox.DataBindings.Add( new Binding( "Image", this.trustPersonBindingSource, "Photo", true, DataSourceUpdateMode.OnPropertyChanged ) );
      this.streetTextBox.DataBindings.Add( new Binding( "Text", this.trustPersonBindingSource, "Address.Street", true, DataSourceUpdateMode.OnPropertyChanged ) );
      this.zipcodeTextBox.DataBindings.Add( new Binding( "Text", this.trustPersonBindingSource, "Address.Zipcode", true, DataSourceUpdateMode.OnPropertyChanged ) );
      this.cityTextBox.DataBindings.Add( new Binding( "Text", this.trustPersonBindingSource, "Address.City", true, DataSourceUpdateMode.OnPropertyChanged ) );


      trustPersonBindingSource.Position = selectedId;
    }

    public TrustPersonForm( BusinessObjects.TrustPersons trustPersons, int selectedId, int childId )
      : this( trustPersons, selectedId ) {
      this.childId = childId;
    }

    #endregion

    #region - Events -

    private void TrustPersonForm_Load( object sender, EventArgs e ) {
      zipcodeList = zipcodeBll.GetAllZipcodes( );
      foreach ( TrustPerson person in trustPersonList ) {
        originalList.Add( person.Copy( ) );
      }

    }

    private void photoButton_Click( object sender, EventArgs e ) {
      if ( openPictureFileDialog.ShowDialog( ) == DialogResult.OK ) {
        Image photo = Image.FromFile( openPictureFileDialog.FileName );
        ( ( TrustPerson ) this.trustPersonBindingSource.Current ).Photo = photo;
      }
      trustPersonBindingSource.ResetBindings( false );
    }

    private void bindingNavigatorMoveFirstItem_Click( object sender, EventArgs e ) {
      Navigate( PresentationHelper.BindingNavigatorMoveType.First );
    }

    private void bindingNavigatorMovePreviousItem_Click( object sender, EventArgs e ) {
      Navigate( PresentationHelper.BindingNavigatorMoveType.Previous );
    }

    private void bindingNavigatorMoveNextItem_Click( object sender, EventArgs e ) {
      Navigate( PresentationHelper.BindingNavigatorMoveType.Next );
    }

    private void bindingNavigatorMoveLastItem_Click( object sender, EventArgs e ) {
      Navigate( PresentationHelper.BindingNavigatorMoveType.Last );
    }

    private void deleteButton_Click( object sender, EventArgs e ) {
      bll.DeleteTrustPerson( ( TrustPerson ) trustPersonBindingSource.Current );
    }

    private void saveButton_Click( object sender, EventArgs e ) {
      Save( );
    }

    private void readIdCardButton_Click( object sender, EventArgs e ) {
      try {
        BasicCardData data = CardReader.ReadCard( );
        if ( data != null ) {
          nameTextBox.Text = data.Name;
          firstNameTextBox.Text = data.FirstName;
          streetTextBox.Text = data.Street;
          zipcodeTextBox.Text = data.Zipcode;
          cityTextBox.Text = data.City;
          bool zipcodeExists = false;
          foreach ( CityZipcode zipcode in zipcodeList ) {
            if ( zipcode.Zipcode == data.Zipcode
              && zipcode.City == data.City
              && zipcode.CountryCode == data.CountryCode ) {
              zipcodeExists = true;
            }
          }
          if ( !zipcodeExists ) {
            CityZipcode zip = new CityZipcode( data.Zipcode, data.City, data.CountryId );
            zip.ZipcodeId = 0;
            zipcodeBll.SaveZipcode( zip );
          }

          nationalNumberTextBox.Text = data.NationalNumber;
        }

      } catch ( be.belgium.eid.BEID_ExNoReader ) {
        MessageBox.Show( "Geen kaartlezer gevonden. \n Controleer of deze goed is aangesloten en probeer opnieuw", "Kaartlezer", MessageBoxButtons.OK, MessageBoxIcon.Exclamation );
      } catch ( be.belgium.eid.BEID_ExNoCardPresent ) {
        MessageBox.Show( "Geen kaart gevonden.", "Kaartlezer", MessageBoxButtons.OK, MessageBoxIcon.Exclamation );
      } catch ( Exception ex ) {
        MessageBox.Show( ex.ToString( ) + "\n" + ex.Message, "Kaartlezer fout", MessageBoxButtons.OK, MessageBoxIcon.Error );
      }

    }

    private void searchZipcodeButton_Click( object sender, EventArgs e ) {
      ZipcodeListForm zipcodeForm = new ZipcodeListForm( );
      if ( zipcodeForm.ShowDialog( ) == DialogResult.OK ) {
        this.zipcodeTextBox.Text = zipcodeForm.Zipcode.Zipcode;
        this.cityTextBox.Text = zipcodeForm.Zipcode.City;
        ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.Zipcode = zipcodeForm.Zipcode.Zipcode;
        ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.ZipcodeId = zipcodeForm.Zipcode.ZipcodeId;
        ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.City = zipcodeForm.Zipcode.City;
        ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.CountryCode = zipcodeForm.Zipcode.CountryCode;
        ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.CountryId = zipcodeForm.Zipcode.CountryId;
        ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.CountryName = zipcodeForm.Zipcode.CountryName;
      }
    }

    private void zipcodeTextBox_Leave( object sender, EventArgs e ) {
      bool found = false;
      if ( !string.IsNullOrEmpty( zipcodeTextBox.Text ) ) {
        foreach ( CityZipcode zipcode in zipcodeList ) {
          if ( zipcode.Zipcode == zipcodeTextBox.Text ) {
            ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.Zipcode = zipcode.Zipcode;
            ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.ZipcodeId = zipcode.ZipcodeId;
            ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.City = zipcode.City;
            ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.CountryCode = zipcode.CountryCode;
            ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.CountryId = zipcode.CountryId;
            ( ( TrustPerson ) trustPersonBindingSource.Current ).Address.CountryName = zipcode.CountryName;

            found = true;
            break;
          }
        }
        if ( !found ) {
          extendedErrorProvider.SetError( zipcodeTextBox, "Postcode niet gevonden." );
        }
      }
    }

    private void pictureCloseButton_Click( object sender, EventArgs e ) {
      if ( MessageBox.Show( "Foto verwijderen?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question ) == DialogResult.Yes ) {
        ( ( TrustPerson ) trustPersonBindingSource.Current ).Photo = null;
        photoPictureBox.Image = null;
        pictureCloseButton.Visible = false;
      }

    }

    private void TrustPersonForm_FormClosing( object sender, FormClosingEventArgs e ) {
      bool? saved = TrySave( );
      if ( saved == null ) {
        e.Cancel = true;
      } else if ( saved == false ) {
        e.Cancel = false;
      }
    }

    #endregion

    #region - Private methods -

    private void Navigate( PresentationHelper.BindingNavigatorMoveType navi ) {
      if ( TrySave( ) != null ) {
        PresentationHelper.MoveBinding( this.trustPersonBindingSource, navi );
      }
    }

    private void MoveTrustPerson( PresentationHelper.BindingNavigatorMoveType navi ) {
      switch ( navi ) {
        case PresentationHelper.BindingNavigatorMoveType.Next:
          trustPersonBindingSource.MoveNext( );
          break;
        case PresentationHelper.BindingNavigatorMoveType.Previous:
          trustPersonBindingSource.MovePrevious( );
          break;
        case PresentationHelper.BindingNavigatorMoveType.First:
          trustPersonBindingSource.MoveFirst( );
          break;
        case PresentationHelper.BindingNavigatorMoveType.Last:
          trustPersonBindingSource.MoveLast( );
          break;
        default:
          break;
      }
    }

    private void UndoChanges( ) {
      extendedErrorProvider.Clear( );

      TrustPerson current = ( TrustPerson ) trustPersonBindingSource.Current;
      for ( int i = 0; i < originalList.Count; i++ ) {
        if ( current.Id.Equals( originalList[ i ].Id ) ) {
          current = originalList[ i ].Copy( );
          break;
        }
      }

      for ( int i = 0; i < trustPersonList.Count; i++ ) {
        if ( ( ( TrustPerson ) trustPersonBindingSource.Current ).Id.Equals( trustPersonList[ i ].Id ) ) {
          trustPersonList[ i ] = ( ( TrustPerson ) trustPersonBindingSource.Current ).Copy( );
          break;
        }
      }
    }

    private bool? TrySave( ) {
      bool? saved = null;
      if ( trustPersonBindingSource.Current != null && ( ( TrustPerson ) trustPersonBindingSource.Current ).HasChanged ) {
        DialogResult result = MessageBox.Show( "Wijzigingen bewaren?", "Wijzigingen", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question );
        if ( result == DialogResult.Yes ) {
          saved = Save( );
        } else if ( result == DialogResult.No ) {
          UndoChanges( );
          saved = false;
        }
      } else {
        saved = false;
      }
      return saved;
    }

    private bool? Save( ) {
      bool? saved = null;
      try {
        if ( ValidateChildren( ) ) {
          bll.SaveTrustPerson( ( TrustPerson ) trustPersonBindingSource.Current );
          for ( int i = 0; i < originalList.Count; i++ ) {
            if ( ( ( TrustPerson ) trustPersonBindingSource.Current ).Id.Equals( originalList[ i ].Id ) ) {
              originalList[ i ] = ( ( TrustPerson ) trustPersonBindingSource.Current ).Copy( );
              break;
            }
          }
          saved = true;
        } else {
          saved = null;
        }
      } catch ( DCMSExceptions.BusinessException ex ) {
        MessageBox.Show( "Fout bij bewaren.\n" + ex.Message, "Bewaarfout", MessageBoxButtons.OK, MessageBoxIcon.Error );
      }
      return saved;
    }

    #endregion

    #region - Validation -

    private void nameTextBox_Validating( object sender, CancelEventArgs e ) {
      extendedErrorProvider.SetError( nameTextBox, "" );

      if ( string.IsNullOrEmpty( nameTextBox.Text ) ) {
        extendedErrorProvider.SetError( nameTextBox, "Naam is verplicht." );
        extendedErrorProvider.SetIconAlignment( nameTextBox, ErrorIconAlignment.MiddleLeft );
        e.Cancel = true;
      }
    }

    private void phoneTextBox_Validating( object sender, CancelEventArgs e ) {
      extendedErrorProvider.SetError( phoneTextBox, "" );
      if ( string.IsNullOrEmpty( phoneTextBox.Text ) && string.IsNullOrEmpty( gsmTextBox.Text ) ) {
        extendedErrorProvider.SetError( phoneTextBox, "Minstens 1 telefoonnr. nodig." );
        extendedErrorProvider.SetIconAlignment( phoneTextBox, ErrorIconAlignment.MiddleLeft );
        e.Cancel = true;
      }

    }

    private void emailTextBox_Validating( object sender, CancelEventArgs e ) {
      extendedErrorProvider.SetError( emailTextBox, "" );
      if ( !string.IsNullOrEmpty( emailTextBox.Text ) ) {
        if ( !PresentationHelper.VaildateEmailString( emailTextBox.Text ) ) {
          extendedErrorProvider.SetError( emailTextBox, "Ongeldig formaat." );
          e.Cancel = true;
        }
      }
    }

    #endregion


  }
}
